package models

import (
	"context"
	"fmt"
	"github.com/redis/go-redis/v9"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
)

var (
	err error
	DB  *gorm.DB
	Rdb *redis.Client
	Ctx = context.Background()
)

func ConfigInit() {
	viper.SetConfigFile("conf/config.yaml")
	if err = viper.ReadInConfig(); err != nil {
		log.Println("配置文件读取失败", err)
		return
	} else {
		config := viper.AllSettings()
		log.Println("配置文件读取成功", config)
	}
}

func MysqlInit() {
	host := viper.GetString("mysql.host")
	port := viper.GetString("mysql.port")
	username := viper.GetString("mysql.username")
	password := viper.GetString("mysql.password")
	database := viper.GetString("mysql.database")

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True", username, password, host, port, database)

	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})

	if err != nil {
		log.Println("Mysql连接失败", err)
		return
	} else {
		log.Println("Mysql连接成功")
	}

	err = DB.AutoMigrate(&Store{})
	if err != nil {
		log.Println("Mysql数据表迁移失败", err)
		return
	} else {
		log.Println("Mysql数据表迁移成功")
	}
}

func RedisInit() {
	host := viper.GetString("redis.host")
	port := viper.GetString("redis.port")
	password := viper.GetString("redis.password")
	database := viper.GetInt("redis.database")

	Addr := fmt.Sprintf("%s:%s", host, port)

	Rdb = redis.NewClient(&redis.Options{
		Addr:     Addr,
		Password: password, // 没有密码，默认值
		DB:       database, // 默认DB 0
	})

	err = Rdb.Ping(Ctx).Err()
	if err != nil {
		log.Println("Redis连接失败", err)
		return
	} else {
		log.Println("Redis连接成功")
	}
}
